<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3">
        <el-select
          v-model="search.filter_project_id"
          filterable
          clearable
          placeholder="请选择项目"
          @change="fetchModuleData">
          <el-option
            v-for="item in search.project_options"
            :key="item.id"
            :label="item.project_name"
            :value="item.id">
          </el-option>
      </el-select>
      </el-col>
      <el-col :span="3">
        <el-select
          v-model="search.filter_module_id"
          filterable
          clearable
          loading-text="loading"
          placeholder="请选择模块">
          <el-option
            v-for="item in search.module_options"
            :key="item.id"
            :label="item.module_name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-input
          placeholder="请输入文件名称"
          prefix-icon="el-icon-search"
          v-model="search.name"
          @keyup.enter.native="SearchFile()">
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" icon="el-icon-search" round @click="SearchFile()">搜索</el-button>
      </el-col>
    </el-row>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" min-width="3%">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="文件名称" min-width="12%">
        <template slot-scope="scope">
          <el-link @click="download(scope.row.id, scope.row.name)" style="color:#298abd">{{scope.row.name == '' ? '-' : scope.row.name}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="所属项目" min-width="7%" align="center">
        <template slot-scope="scope">
          {{ scope.row.belong_project }}
        </template>
      </el-table-column>
      <el-table-column label="所属模块" min-width="7%" align="center">
        <template slot-scope="scope">
          {{ scope.row.belong_module }}
        </template>
      </el-table-column>
      <el-table-column label="文件大小(KB)" min-width="5%" align="center">
        <template slot-scope="scope">
          {{ scope.row.file_size }}
        </template>
      </el-table-column>
      <el-table-column label="上传人员" min-width="8%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="操作" label="更新时间" min-width="8%">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ $common.formatDateTime(scope.row.update_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="8%" align="center">
        <template slot-scope="scope">
          <el-button-group>
            <el-tooltip content="下载" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-download"
                @click="download(scope.row.id, scope.row.name)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="bottom" effect="light">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="del(scope.row.id)">
              </el-button>
            </el-tooltip>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page_num"
      :page-sizes="[10, 20]"
      :page-size="pagination.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>
  </div>
</template>

<script>
import { getFileList, deleteFile, downloadFile } from '@/api/file/table'
import { getProjectList } from '@/api/project/table'
import { getModuleList } from '@/api/module/table'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      search: {
        project_options: [],
        module_options: [],
        filter_project_id: null,
        filter_module_id: null,
        name: ''
      },
      pagination: {
        total: 0,
        page_current: 1,
        page_num: 1,
        page_size: 10
      },
      list: null,
      listLoading: true,
      ispagination: false
    }
  },
  created() {
    this.fetchProjectData()
    this.fetchFileData()
  },
  methods: {
    fetchProjectData() {
      getProjectList().then(response => {
        this.search.project_options = response.results
      })
    },
    fetchModuleData() {
      this.search.filter_module_id = null
      if (this.search.filter_project_id) {
        var params = { 'belong_project': this.search.filter_project_id }
        getModuleList(params).then(response => {
          this.search.module_options = response.results
        })
      }
    },
    fetchFileData() {
      var params = {}

      params['ordering'] = '-update_time'
      this.listLoading = true
      getFileList(params).then(response => {
        this.list = response.results
        this.listLoading = false
        this.pagination.total = response.count
      })
    },
    SearchFile: function() {
      var params = {}
      if (this.search.filter_project_id) {
        for (var i = 0; i < this.search.project_options.length; i++) {
          if (this.search.filter_project_id === this.search.project_options[i].id) {
            params['project'] = this.search.project_options[i].id
          }
        }
      }
      if (this.search.filter_module_id) {
        params['module'] = this.search.filter_module_id
      }

      if (this.search.name) {
        params['search'] = this.search.name
      }
      if (this.ispagination){
        params['page_num'] = this.pagination.page_num
        params['page_size'] = this.pagination.page_size
      }else{
        params['page_num'] = 1
        params['page_size'] = this.pagination.page_size
      }
      params['ordering'] = '-update_time'

      this.listLoading = true
      getFileList(params).then(response => {
        this.list = response.results
        this.listLoading = false
        this.pagination.total = response.count
      })
      if (this.ispagination == false){
        this.pagination.page_num = 1
       }
        this.ispagination = false
     },

    del(arg){
      this.$confirm('此操作将删除文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      var params = {}
      params['id'] = arg
      deleteFile(params).then(response => {
        if (response.status == "000000") return
          this.SearchFile()
      })
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    download(id, name) {
      var params = {}
      params['id'] = id
      downloadFile(params).then(response => {
        console.log(response)
        if (response.size === 88) {
             this.$message.error('请求的文件不存在，请确认后再操作')
          } else {
              const blob = new Blob([response])
              let fileName = name
              const link = document.createElement('a')
              link.download = fileName
              link.style.display = 'none'
              link.href = URL.createObjectURL(blob)
              document.body.appendChild(link)
              link.click()
              URL.revokeObjectURL(link.href)
              document.body.removeChild(link)
        }
      })
    },

    handleSizeChange: function(val) {
      this.pagination.page_size = val
      this.SearchFile()
    },
    handleCurrentChange: function(val) {
      this.ispagination = true
      this.pagination.page_num = val
      this.SearchFile()
    }
  }
}
</script>
